package com.example.xyr.myapplication.utils

import net.sourceforge.pinyin4j.PinyinHelper
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination


/**
 * Created by ylcf on 2018/9/5.
 */
class PinYinUtils {

    companion object {
        fun getPinYin(name: String): String {
            try {
                var result = ""
                //利用pinyin4j进行汉字到汉语拼音的转换
                //1)设定一下拼音的格式
                val format = HanyuPinyinOutputFormat()
                format.caseType = HanyuPinyinCaseType.UPPERCASE
                format.toneType = HanyuPinyinToneType.WITHOUT_TONE
                //2)把name进行逐字的转换
                val sb = StringBuilder()
                for (i in 0 until name.length) {
                    val s = name.substring(i, i + 1)
                    if (s.matches("[\u4e00-\u9fff]".toRegex())) {
                        val arg0 = name[i]
                        val py = PinyinHelper.toHanyuPinyinStringArray(arg0, format)
                        sb.append(py[0])
                    } else if (s.matches("[a-zA-Z]".toRegex())) {
                        sb.append(s.toUpperCase())
                    } else {
                        sb.append("#")
                    }
                }
                result = sb.toString()
                return result
            } catch (e: BadHanyuPinyinOutputFormatCombination) {
                e.printStackTrace()
                throw RuntimeException("不正确的汉语拼音格式")
            }


        }
    }
}